import { Component, OnInit, Input, ViewChild } from '@angular/core';
import { CountdownComponent } from 'ngx-countdown';
import { BasicService } from '../../../@core/data/basic.service';
// 消息提醒
import { ToasterConfig } from 'angular2-toaster';
import { NotificationsService } from '../../../@core/utils/notifications.service';
import { ActivatedRoute, Router } from '@angular/router';
import { FroalaComponent } from '../../../@theme/components/index';
@Component({
    selector: 'ngx-doexam',
    styleUrls: ['./doexam.component.scss'],
    templateUrl: './doexam.component.html',
})
export class DoexamComponent implements OnInit {
    @Input() paperId = 1;
    config: ToasterConfig;
    paper: any;
    description: any;
    hidePaperCard = true;

    /**
     * 试题信息列表，index对应试题
     */
    questionList: any;
    currentIndex = 0;
    currentQuestion: any;

    constructor(private service: BasicService,
        private notificationsService: NotificationsService,
        private router: Router,
        public route: ActivatedRoute) {
        this.paper = {};
        this.description = {};
    }

    ngOnInit(): void {
        this.route.params.subscribe(param => {
            this.paperId = param.paperId;
            const _self = this;
            // 获取试卷
            const getPaper = function () {
                return new Promise(function (resolve, reject) {
                    _self.service.getOne('papers/' + _self.paperId).subscribe((data: any) => {
                        resolve(data.row);
                    });
                });
            };
            // 获取试题类型
            const getQtype = function () {
                return new Promise(function (resolve, reject) {
                    _self.service.getOne('configs/findByCtype?ctype=question_type')
                        .subscribe((data: any) => {
                            resolve(data.rows);
                        });
                });
            };
            (async () => {
                this.paper = await getPaper();
                if (typeof (this.paper.description) === 'string') {
                    this.description = JSON.parse(this.paper.description);
                }
                const qtypes = await getQtype() as Array<any>;
                this.questionList = [];
                let qname = '-1';
                for (const qtype of qtypes) {
                    qname = qtype['name'];
                    if (this.description[qname]) {
                        for (const q of this.description[qname]) {
                            this.questionList.push(q);
                        }
                    }
                }
                this.beginTimer();
            })();
        });
    }

    @ViewChild('countdown') counter: CountdownComponent;

    onFinished() {
        if (this.questionList) {
            this.save();
        }
    }
    beginTimer() {
        if (this.counter) {
            this.counter.begin();
        }
    }

    /**
     * 提交试卷
     */
    save() {
        // 获取当前试卷
        this.paper.description = JSON.stringify(this.questionList);
        const userId = 1;
        this.service.create('papers/createAchievement/' + userId, this.paper).subscribe(
            data => {
                this.notificationsService.showToast('success', '操作', '<b>保存 <em>成功！</em></b>');
                // 跳转到历史成绩
                this.counter.stop();
                this.router.navigate(['/pages/learn/myhispaper']);
            },
            err => {
                this.notificationsService.showToast('error', '操作', '<b>保存 <em>失败！</em></b>');
                console.error('Error saving!', err);
            },
        );
    }

    /**
     * 显示或者隐藏答题卡
     */
    hidePaperCardHandle() {
        if (this.hidePaperCard) {
            this.hidePaperCard = !this.hidePaperCard;
        } else {
            this.hidePaperCard = !this.hidePaperCard;
        }
    }

    /**
     * 上一题
     */
    previousQuestion() {
        if (this.currentIndex > 0) {
            this.currentIndex--;
        } else {
            this.currentIndex = this.questionList.length - 1;
        }
    }

    /**
     * 下一题
     */
    nextQuestion() {
        if (this.currentIndex >= this.questionList.length - 1) {
            this.currentIndex = 0;
        } else {
            this.currentIndex++;
        }
    }

    /**
     * 跳到当前选择的试题
     * @param event
     */
    goToQuestion(event) {
        const index = event.target.id;
        this.currentIndex = Number.parseInt(index);
    }

    /**
     * 对于富文本试题答案赋值
     * @param event
     */
    froalaContent(event) {
        if (event && event.length > 0 && event.indexOf('=') > 0) {
            const index = event.indexOf('=');
            const key = event.substring(0, index);
            const val = event.substring(index + 1);
            this.questionList[this.currentIndex].youranswer = val;
        }
    }
}

